package net.zigin.nhi.could.waste.exception;

import lombok.extern.slf4j.Slf4j;
import net.zigin.commons.util.StringUtil;
import net.zigin.nhi.could.waste.constants.CommonConstants;
import net.zigin.nhi.could.waste.vo.JsonForResult;
import org.springframework.dao.DataAccessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 免疫规划云全局异常处理
 *
 * @author mgw1986
 * @version V1.0
 * @date 2018/12/3 9:20
 */
@Slf4j
@RestControllerAdvice
public class EpiCloudAdvice {

    @ExceptionHandler(Exception.class)
    public JsonForResult<Object> exceptionHandler(Exception e) {
        log.error("EpiCloudAdvice exceptionHandler:{}", e.getLocalizedMessage(), e);
        return JsonForResult.builder().success(false).message(CommonConstants.SERVICE_ERROR).build();
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public JsonForResult<Object> missingParameterHandler(MissingServletRequestParameterException e) {
        return JsonForResult.builder().success(false).message(e.getMessage()).build();
    }

    @ExceptionHandler(value = {DataAccessException.class})
    public JsonForResult DataAccessExceptionHandler(DataAccessException e) {
        //Spring的dao为了统一处理，屏蔽了与特定技术相关的异常,例如SQLException或HibernateException,
        log.error("EpiCloudAdvice sqlExceptionHandler:{}", e.getMessage());
        return JsonForResult.builder().success(false).message(CommonConstants.SQL_ERROR).build();
    }

    @ExceptionHandler(value = {EpiCloudException.class, RuntimeException.class})
    public JsonForResult<Object> epiCloudExceptionHandler(RuntimeException e) {
        log.error("EpiCloudAdvice epiCloudExceptionHandler:{}", e.getLocalizedMessage(), e);
        String message = e.getMessage();
        if (StringUtil.isNullOrEmpty(message)) {
            return JsonForResult.builder().success(false).message(CommonConstants.UNKNOWN_ERROR).build();
        }
        if (message.contains("com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException")) {
            log.error("EpiCloudAdvice epiCloudExceptionHandler:{}", message);
            return JsonForResult.builder().success(false).message(CommonConstants.UNKNOWN_ERROR).build();
        }
        return JsonForResult.builder().success(false).message(e.getMessage()).build();
    }

    @ExceptionHandler(value = {HttpMessageNotReadableException.class})
    public JsonForResult handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        //Required request body is missing
        log.error("HttpMessageNotReadableException :{}",e.getMessage());
        return JsonForResult.builder().success(false).message(CommonConstants.BODY_NULL_ERROR).build();
    }
}
